package com.woyou;

import java.lang.Thread.UncaughtExceptionHandler;

import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.EApplication;

import android.app.Application;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.util.Log;
import cn.jpush.android.api.JPushInterface;

import com.umeng.analytics.MobclickAgent;
import com.woyou.service.JPushService;
import com.woyou.service.NetWorkCenter;
import com.woyou.service.NetWorkCenter.ConnectionChangeReceiver;

@EApplication
public class MyApplication extends Application {

	protected static final String TAG = "MyApplication";
	public static boolean isShowLog = false;

	@Bean
	NetWorkCenter mNetWorkCenter;

	@Override
	public void onCreate() {
		super.onCreate();
		// String deviceInfo_YM =
		// DeviceUtils.getDeviceInfo_YM(getApplicationContext());

		init();
		configUncaughtExceptionHandler();
		// 打印错误日志
		// Thread.setDefaultUncaughtExceptionHandler(new PrintUncaughtException());
		initVersionConstant();
		
	}

	private void initPush() {
		if (JPushInterface.isPushStopped(getApplicationContext())) {
			JPushInterface.resumePush(getApplicationContext());
		}
		JPushService.getInstance(getApplicationContext()).registerMessageReceiver();

	}

	private void initVersionConstant() {
		PackageInfo myVersionManager = null;
		try {
			myVersionManager = getPackageManager().getPackageInfo(
					"com.citaq.ideliver", PackageManager.GET_CONFIGURATIONS);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		Constant.currentVersion = myVersionManager.versionCode;
		Constant.versionName = myVersionManager.versionName;
	}

	// 捕获异常
	private void configUncaughtExceptionHandler() {
		Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {

			@Override
			public void uncaughtException(Thread thread, Throwable ex) {
				Log.e(TAG, "uncaughtException crash", ex);
			}

		});
	}

	private ConnectionChangeReceiver mReceiver;

	private void init() {

		// 友盟关闭默认统计
		MobclickAgent.openActivityDurationTrack(false);
		// MobclickAgent.setDebugMode( true );

		mReceiver = mNetWorkCenter.getConnectionChangeReceiver();
		// 极光推送
		JPushInterface.setDebugMode(true);
		JPushInterface.init(this);
		// 极光推送

		IntentFilter mFilter = new IntentFilter();
		mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
		registerReceiver(mReceiver, mFilter);

		initPush();
	}

	@Override
	protected void finalize() throws Throwable {
		super.finalize();
		unregisterReceiver(mReceiver);
		try {
			JPushService.getInstance(getApplicationContext()).destory();
		} catch (Exception e) {
			Log.e(TAG, e.getMessage());
		}
	}
	

}
